/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mfi.controllers;

import com.mfi.models.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author admin
 */
public class ProductModifyServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            Customer customer = (Customer) request.getSession().getAttribute("account");
            if (customer == null || !customer.getType().equals("admin")) {
                response.sendRedirect("/");
            }
            
            DBConnection connection = new DBConnection();
            String id = request.getParameter("id");
            Product product = connection.selectProduct(id);
            request.setAttribute("product", product);
            
            request.setAttribute("title", "Modify Product");
            
            ArrayList categories = connection.getCategories();
            request.setAttribute("categories", categories);
            
            if (request.getParameter("true") != null) {
                try {
                    
                    Product p = new Product();
                    
                    Map<String, String> map = new HashMap<String, String>();
                    //String dirPath = getServletContext().getRealPath("/uploads").replace("\\", "/") + "/";
                    String dirPath = "D:/ARIES_JSP/hotbite/web/uploads/";
                    
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                            String fieldname = item.getFieldName();
                            String fieldvalue = item.getString();
                            map.put(fieldname, fieldvalue.trim());
                        } else {
                            // Process form file field (input type="file").
                            String filename = item.getName();
                            if (filename.equals("")) {
                                filename = product.getImage();
                            } else {
                                
                                filename = FilenameUtils.getName(item.getName());

                                File filePath = new File(dirPath);

                                if (!filePath.exists()) {
                                    filePath.mkdirs();
                                }

                                File uploadedFile = new File(dirPath + filename);

                                item.write(uploadedFile);
                            }
                            
                            map.put("image", filename);
                        }
                        
                    }
                    
                    out.print(map.get("image"));
                    p.setId(Integer.parseInt(id));
                    p.setName(map.get("name"));
                    p.setCategory_id(Integer.parseInt(map.get("category")));
                    p.setDescription(map.get("description"));
                    p.setImage(map.get("image"));
                    
                    if (connection.modifyProduct(p)) {
                        request.getSession().setAttribute("message", "Product successfully modified!");
                        response.sendRedirect("/manage");
                    } else {
                        request.getSession().setAttribute("error", "Error of a lifetime, saree!");
                        response.sendRedirect("/manage");
                    }

                } catch (FileUploadException e) {
                    throw new ServletException("Cannot parse multipart request.", e);
                }
            } else {
                //request.getSession().setAttribute("error", "Error of a lifetime, saree!");
                request.getRequestDispatcher("/WEB-INF/manage/product/modify.jsp").forward(request, response);
            }
            
        } catch (Exception ex) {
            out.print("WOW");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
